import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(const WebviewLocaleHtml());

class WebviewLocaleHtml extends StatefulWidget {
  const WebviewLocaleHtml({Key? key}) : super(key: key);
  @override
  _WebviewLocaleHtmlState createState() => _WebviewLocaleHtmlState();
}

class _WebviewLocaleHtmlState extends State<WebviewLocaleHtml> {
  late final WebViewController _webViewController;
  bool dialogVisible = false;
  String jsMessage = "";

  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: "Toast",
        onMessageReceived: (JavascriptMessage message) {
          setState(() {
            jsMessage = message.message;
            dialogVisible = true;
          });
        });
  }

  _loadHtmlFromAssets() async {
    String fileHtmlContents = await rootBundle.loadString("assets/test.html");
    _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
            mimeType: "text/html", encoding: Encoding.getByName("utf-8"))
        .toString());
  }

  _showToast(String content) {
    print(content);
    ScaffoldMessenger.of(context)
        .showSnackBar(const SnackBar(content: Text("hah")));
  }

  Widget _dialogWidget(String title) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: SizedBox(
          width: 200.0,
          height: 200.0,
          child: Container(
            color: Colors.white,
            child: Text(title),
          ),
        )
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "flutter demo",
      home: Scaffold(
        appBar: AppBar(title: const Text("webview_locale_html")),
        floatingActionButton: Builder(builder: (BuildContext context) {
          return FloatingActionButton(
            child: const Text("点击调用js"),
            onPressed: () {
//              showDialog(
//                  context: context,
//                  builder: (context) {
//                    return Scaffold(
//                      backgroundColor: Colors.transparent,
//                      body: Center(
//                        child: Column(
//                          mainAxisAlignment: MainAxisAlignment.center,
//                          children: <Widget>[
//                            const SizedBox(
//                              height: 10,
//                            ),
//                            const Text('loading'),
//                          ],
//                        ),
//                      ),
//                    );
//                  });
              _webViewController
                  ?.runJavascriptReturningResult(
                      "callJs('这是flutter 传递给js方法的参数')")
                  ?.then((value) => {print(value)});
            },
          );
        }),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        body: Stack(
          fit: StackFit.expand,
          children: [
            Container(
              child: WebView(
                initialUrl: "",
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels:
                <JavascriptChannel>[_alertJavascriptChannel(context)].toSet(),
                onWebViewCreated: (WebViewController webViewController) {
                  _webViewController = webViewController;
                  _loadHtmlFromAssets();
                }),
            ),
            dialogVisible ? Container(
              decoration: const BoxDecoration(
                color: Colors.black12,
              ),
              child: Center(
                child: Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  width: 200,
                  height: 100,
                  child: Column(
                    children: [
                      Text(jsMessage),
                      MaterialButton(
                          child: const Text("点击我关闭弹窗"),
                          onPressed: () {
                        setState(() {
                          dialogVisible = false;
                        });
                      })
                    ],
                  ),
                ),
              ),
            ) : Container()
          ]
        )
//        Column(
//          children: [
//            WebView(
//                initialUrl: "",
//                javascriptMode: JavascriptMode.unrestricted,
//                javascriptChannels:
//                <JavascriptChannel>[_alertJavascriptChannel(context)].toSet(),
//                onWebViewCreated: (WebViewController webViewController) {
//                  _webViewController = webViewController;
//                  _loadHtmlFromAssets();
//                }),
//            dialogVisible ? _dialogWidget(jsMessage) : Container()
//          ],
//        )
      )
    );
  }
}
